import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Spin, InputNumber, Upload, Input, Calendar, Badge, Empty, Tooltip, Popover, Button, Tabs, Modal, Select, message, Pagination } from 'antd';
import moment from 'moment';
import { PrimaryC, PrimaryGhostC, NoQueryC, SelectC, SecondHeaderC, DATA_ENTRY, AdvancedSearch, ModalC, TableC, FirstHeaderC } from '../../../../comps';
import myStyle from '../index.less';
const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { confirm } = Modal;
const { Option } = Select;
import { fixedNum } from '../../../../utils/utils';
import uuid from 'es6-uuid';
import upImg from '../../../../assets/busi/assetSplit/up_arrow.png';
import downImg from '../../../../assets/busi/assetSplit/down_arrow.png';
import upSelectedImg from '../../../../assets/busi/assetSplit/up_arrow_select.png';
import downSelectedImg from '../../../../assets/busi/assetSplit/down_arrow_select.png';
import TransactionFlow from '../common/TransactionFlow';
import ProductYield from '../common/ProductYield';
import convertFromRawToDraftState from 'draft-js/lib/convertFromRawToDraftState';
@connect(({ survivalManageM, loading }) => ({
  survivalManageM,
  loading,
}))
@Form.create()
export default class TransferInsideC extends PureComponent {
  state = {
    columnsOrigin: undefined, //源产品
    dataSoureOrigin: undefined,
    seletedRowsUp: [], //上方选中行
    seletedRowsDown: [], //下方方选中行
    selectedRowKeysUp: undefined, //上方选中行index
    selectedRowKeysDown: undefined, //下方方选中行index
    columnsTarget: undefined, //目标产品
    dataSoureTarget: undefined, //
    search: null, //存储系列id
    selectProductList: [], //产品下拉列表
    originId: undefined, //源产品id
    targetId: undefined, //目标产品id
    dataSoureTradeList: undefined, //交易流水数据
    updateYeild: new Date().getTime(), //更新产品收益率时间戳
    columnsTrade: undefined, //交易流水columns
    originInitRate: undefined, //源产品的原始收益率
    targetInitRate: undefined, //目标产品的原始收益
    originCurrentRate: undefined, //源产品的当前收益率
    targetCurrentRate: undefined, //目标产品的当前收益率
  };
  componentDidMount() {}
  UNSAFE_componentWillReceiveProps(nextProps) {
    //只要有id传过来，接请求新的数据，不要判断相等
    if (nextProps.args && this.props.args && nextProps.args.timestamp != this.props.args.timestamp) {
      this.props.form.resetFields();
      this.setState(
        {
          search: nextProps.args.id,
          columnsOrigin: undefined, //源产品
          dataSoureOrigin: undefined,
          seletedRowsUp: [], //上方选中行
          seletedRowsDown: [], //下方方选中行
          selectedRowKeysUp: undefined, //上方选中行index
          selectedRowKeysDown: undefined, //下方方选中行index
          columnsTarget: undefined, //目标产品
          dataSoureTarget: undefined, //
          selectProductList: [], //产品下拉列表
          originId: undefined, //源产品id
          targetId: undefined, //目标产品id
          dataSoureTradeList: undefined, //交易流水数据
          updateYeild: new Date().getTime(), //更新产品收益率时间戳
          originInitRate: undefined, //源产品的原始收益率
          targetInitRate: undefined, //目标产品的原始收益
          originCurrentRate: undefined, //源产品的当前收益率
          targetCurrentRate: undefined, //目标产品的当前收益率
        },
        () => {
          this.queryProductIdList(); //获取资产下拉列表
        },
      );
    }
  }
  clearIdList() {
    //清空idList
    this.props.dispatch({
      type: 'survivalManageM/save',
      payload: {
        idList: [],
      },
    });
  }

  //根据子产品ID，获取已分配的资产信息
  queryAssignedAsset = (productId, currentType, flag) => {
    //flag 直接越过对idlist的比对
    const { dataSoureOrigin, dataSoureOrigin_old, originId, targetId, dataSoureTarget, dataSoureTarget_old } = this.state;
    if (!flag && currentType != 'target' && dataSoureTarget && dataSoureTarget.findIndex((item) => item.isEdit == true) > -1) {
      message.warning('当前处于编辑状态!');
      this.originSelect.setSelect(originId);
      return;
    }

    let arr;
    if (currentType == 'target') {
      this.setState({
        //切换目标产品 清除掉选中行和当前table数据
        targetId: productId,
        columnsTarget: undefined,
        dataSoureTarget: undefined,
        selectedRowKeysDown: undefined, //下方方选中行index
        seletedRowsDown: [], //下方方选中行
      });
      this.clearIdList(); //清除idList
      if (dataSoureTarget_old) {
        this.queryAssignedAsset(originId, 'origin', 'flag'); //切换目标产品 更新源产品
      }
    } else {
      //源产品
      //资产变动的产品id 要进行存储 来用于试算的入参idList
      if (!flag && dataSoureOrigin && dataSoureOrigin.length) {
        //切换源产品时 对当前源产品数据 存入idList
        arr = this.props.survivalManageM.idList;
        // 没有数据变动 也可以进行试算    //判断当前源产品是否已经存在于idlist //不存在则新增 因源产品是多对一的关系，需要识别存储idList
        if (arr.findIndex((item) => item.productId == originId) < 0) {
          if (originId !== targetId) {
            arr.push({
              productId: originId,
              assignData: this.formAssignData(dataSoureOrigin),
            });
          }
        } else {
          //存在 则更新数据  将最新的数据替换原数据

          arr.map((item) => {
            if (item.productId == originId) {
              item.assignData = this.formAssignData(dataSoureOrigin);
            }
          });
        }

        this.props.dispatch({
          type: 'survivalManageM/save',
          payload: {
            idList: arr,
          },
        });
      }
      this.setState({
        //切换产品 清除掉选中行和当前table数据
        originId: productId,
        columnsOrigin: undefined,
        dataSoureOrigin: undefined,
        selectedRowKeysUp: undefined,
        seletedRowsUp: [],
      });
    }
    this.props.dispatch({
      type: 'survivalManageM/queryAssignedAsset',
      payload: {
        productId: productId,
        currentPage: 1,
        numInPage: 5000,
      },
      callback: (type, data) => {
        if (type == 'success') {
          data.dataSource.map((item) => {
            item.averageMarketVal = parseFloat(Number(item.marketValue) / Number(item.allocation));
          });
          if (currentType != 'target') {
            //    if(//找出修改过的产品 对应的 资产列表 变更数量和成本价)
            if (arr && arr.length && !flag) {
              //判断是否有idlist,再判断选择的源产品是否有修改过
              if (arr.find((item) => item.productId == productId)) {
                //修改过的资产列表 修改下数量和key
                let sumRate02 = 0;
                data.dataSource.map((item, key) => {
                  //取原始数据的 收益率
                  sumRate02 = sumRate02 + item.assetRate * 1 * (item.weight * 1);
                });
                data.dataSource.map((item, key) => {
                  item.isEdit = false;
                  var tempId = arr.find((item) => item.productId == productId);
                  tempId.assignData &&
                    tempId.assignData.map((asset) => {
                      if (item.id == asset.id) {
                        item.oldAllocation = item.allocation;
                        item.allocation = asset.allocation;
                        item.key = asset.key;
                        (item.marketValue = asset.marketValue), //为了计算市值
                          (item.weight = asset.weight);
                      }
                    });
                  item.averageMarketVal = parseFloat(Number(item.marketValue) / Number(item.allocation));
                });

                this.setState({
                  originInitRate: parseFloat(sumRate02 * 100).toFixed(4), //原始收益率
                  columnsOrigin: data.columns || [],
                  dataSoureOrigin: JSON.parse(JSON.stringify(data.dataSource)),
                  dataSoureOrigin_old: JSON.parse(JSON.stringify(data.dataSource)),
                });
              } else {
                let sumRate01 = 0;
                data.dataSource.map((item, key) => {
                  item.key = uuid(8);
                  item.isEdit = false;
                  sumRate01 = sumRate01 + item.assetRate * 1 * (item.weight * 1);
                });
                this.setState({
                  originInitRate: parseFloat(sumRate01 * 100).toFixed(4), //原始收益率
                  columnsOrigin: data.columns || [],
                  dataSoureOrigin: JSON.parse(JSON.stringify(data.dataSource)),
                  dataSoureOrigin_old: JSON.parse(JSON.stringify(data.dataSource)),
                });
              }
            } else {
              let sumRate = 0;
              data.dataSource &&
                data.dataSource.map((item, key) => {
                  item.key = uuid(8);
                  item.isEdit = false;
                  sumRate = sumRate + item.assetRate * 1 * (item.weight * 1);
                });
              this.setState({
                originInitRate: parseFloat(sumRate * 100).toFixed(4), //原始收益率
                columnsOrigin: data.columns || [],
                dataSoureOrigin: JSON.parse(JSON.stringify(data.dataSource)),
                dataSoureOrigin_old: JSON.parse(JSON.stringify(data.dataSource)),
              });
            }
          } else {
            let sumRate1 = 0;
            data.dataSource.map((item, key) => {
              item.isOrigin = true;
              item.key = key;
              sumRate1 = sumRate1 + item.assetRate * 1 * (item.weight * 1);
            });
            this.setState({
              targetInitRate: parseFloat(sumRate1 * 100).toFixed(4), //实际收益率
              columnsTarget: data.columns || [],
              dataSoureTarget: JSON.parse(JSON.stringify(data.dataSource)),
              dataSoureTarget_old: JSON.parse(JSON.stringify(data.dataSource)),
            });
          }
        } else {
          if (type != 'target') {
            this.setState({
              originInitRate: undefined,
              columnsOrigin: [],
              dataSoureOrigin: [],
            });
          } else {
            this.setState({
              targetInitRate: undefined,
              columnsTarget: [],
              dataSoureTarget: [],
            });
          }
        }
      },
    });
  };
  //根据系列产品ID，获取资产下拉列表
  queryProductIdList = () => {
    const { search } = this.state;
    this.props.dispatch({
      type: 'survivalManageM/queryProductIdList',
      payload: {
        seriesProductId: search,
        currentPage: 1,
        numInPage: 5000,
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            selectProductList: data.map((item) => {
              return { value: item.productId, title: item.productName };
            }),
          });
        } else {
          this.setState({
            selectProductList: [],
          });
        }
      },
    });
  };
  //点击编辑按钮 切换为编辑状态 显示保存按钮
  clickEdit = (type, record) => {
    const { dataSoureTarget, originId } = this.state;
    dataSoureTarget.map((item) => {
      if (item.key == record.key) {
        if (type == 'edit') {
          if (item.productId && item.productId != originId) {
            message.error('该资产不在当前源产品中,不支持编辑');
            return;
          }
        }
        item.isEdit = type == 'edit' ? true : false;
      }
    });
    this.setState({
      dataSoureTarget: [...dataSoureTarget],
    });
  };
  //点击保存按钮
  saveRow = (record) => {
    const { dataSoureOrigin, dataSoureTarget } = this.state;
    if (record.allocation === 0 || record.allocation === undefined) {
      message.warning('数量必须大于0');
      return;
    }
    let msg;
    let currentRowOld = this.state.dataSoureOrigin_old.find((item) => item.key == record.key);

    dataSoureOrigin.map((item) => {
      if (item.key == record.key) {
        if (!currentRowOld) return;
        var oldNum = currentRowOld.oldAllocation ? currentRowOld.oldAllocation * 1 : currentRowOld.allocation * 1;
        if (oldNum - record.allocation < 0) {
          msg = '数量应小于源产品对应资产的数量';
          message.warning(msg);
          return;
        } else {
          //更新市值 市值=数量*平均市值  当前行的市值/所有的市值之和=权重
          record.marketValue = parseFloat(Number(record.allocation) * Number(record.averageMarketVal)); //目标的市值
          item.allocation = oldNum - Number(record.allocation);
          item.marketValue = parseFloat(Number(item.allocation) * Number(item.averageMarketVal)); //源产品的市值
          msg = '通过';
        }
      }
    });
    if (msg == '通过') {
      let sumOrigin = 0; //市值之和
      dataSoureOrigin.map((item) => {
        sumOrigin = sumOrigin + Number(item.marketValue);
      });
      dataSoureOrigin.map((item) => {
        item.weight = parseFloat(Number(item.marketValue) / sumOrigin);
      });
      let sumTarget = 0; //市值之和
      dataSoureTarget.map((item) => {
        sumTarget = sumTarget + Number(item.marketValue);
      });

      dataSoureTarget.map((item) => {
        item.weight = parseFloat(Number(item.marketValue) / sumTarget);
      });

      this.setState({
        dataSoureOrigin: [...dataSoureOrigin],
        dataSoureTarget: [...dataSoureTarget],
      });
      this.clickEdit('save', record);
      return;
    }
    if (!msg) {
      this.clickEdit('save', record);
    }
  };
  //点击试算
  tryCalc = (type) => {
    const { dataSoureTarget, dataSoureOrigin, dataSoureOrigin_old, originId, targetId } = this.state;
    const {
      survivalManageM: { idList },
    } = this.props;
    if (originId === targetId) {
      message.warning('源产品和目标产品必须不同!');
      return;
    }
    if (dataSoureTarget && !dataSoureTarget.length) return;
    if (dataSoureTarget.findIndex((item) => item.isEdit == true) > -1) {
      message.warning('当前处于编辑状态!');
      return;
    }
    idList.map((item) => {
      if (item.productId == originId) {
        //源产品已存在目标产品中 则修改格式
        item.assignData = this.formAssignData(dataSoureOrigin);
      }
    });
    const arr = JSON.parse(JSON.stringify(idList));
    //资产变动的产品id 要进行存储 来用于试算的入参idList
    if (dataSoureOrigin && dataSoureOrigin.length && type != 'smart') {
      if (arr.findIndex((item) => item.productId == originId) < 0 || !arr.length) {
        //判断当前源产品是否已经存在于idlist 不存在则push
        arr.push({
          productId: originId,
          assignData: this.formAssignData(dataSoureOrigin),
        });
      }
    }
    const arr1 = [];
    if (type == 'smart') {
      //智能转仓这里是一对一 而不是多对一
      arr1.push({
        productId: originId,
        assignData: this.formAssignData(dataSoureOrigin),
      });
      arr1.push({
        productId: targetId,
        assignData: this.formAssignData(dataSoureTarget),
      });
      this.smartTrans(arr1);
      return;
    }
    arr.push({
      //目标产品最后存入idList
      productId: targetId,
      assignData: this.formAssignData(dataSoureTarget),
    });
    if (type == 'confirm') {
      //点击确定 清空idlist
      this.confirmAdust(arr);
      return;
    } else {
      //点击试算 缓存除当前两个产品的数据 因为每次提交前都会重新存入源产品和目标产品
      this.saveIdlist(); //设置idList
    }
    this.props.dispatch({
      type: 'survivalManageM/tryCalc',
      payload: {
        idList: arr,
      },
      callback: (type, data) => {
        if (type == 'success') {
          //试算之后 只更新流水
          this.setState({
            dataSoureTradeList: data.dataSource || [],
            columnsTrade: data.columns || [],
          });
        }
      },
    });
  };
  //formAssignData  将入参数据改造下
  formAssignData = (data) => {
    if (!data) return;
    let arr = data.map((item) => {
      return {
        id: item.id,
        allocation: item.allocation * 1,
        price: item.price * 1,
        marketValue: item.marketValue * 1, //计算市值 收益率
        weight: item.weight * 1,
      };
    });
    return arr || [];
  };
  saveIdlist = () => {
    //x试算之后 idList保留当前源产品和目标产品以外的数据
    const {
      survivalManageM: { idList },
    } = this.props;
    const { originId, targetId } = this.state;
    if (idList && idList.length) {
      // 去掉当前源产品和目标产品，保留额外的产品
      const tempArr = [];
      idList.map((proudct) => {
        if (proudct.productId != originId && proudct.productId != targetId) {
          tempArr.push(proudct);
        }
      });

      this.props.dispatch({
        type: 'survivalManageM/save',
        payload: {
          idList: tempArr,
        },
      });
    }
  };
  //点击智能转仓
  smartTrans = (arr) => {
    const {
      survivalManageM: { idList },
    } = this.props;
    const { originId, targetId } = this.state;
    this.props.dispatch({
      type: 'survivalManageM/smartTrans',
      payload: {
        idList: arr,
      },
      callback: (data) => {
        if (data) {
          let originData;
          let targetData;
          Object.keys(data).map((item) => {
            if (arr[0].productId == item) {
              //源产品
              originData = data[item];
              originData &&
                originData.map((item, key) => {
                  item.key = uuid(8);
                  item.isEdit = false;
                  item.averageMarketVal = parseFloat(Number(item.marketValue) / Number(item.allocation));
                });
            }
            if (arr[1].productId == item) {
              //目标产品
              targetData = data[item];
              targetData &&
                targetData.map((item, key) => {
                  item.isOrigin = true;
                  item.key = key;
                  item.averageMarketVal = parseFloat(Number(item.marketValue) / Number(item.allocation));
                });
            }
          });

          this.saveIdlist();

          this.setState(
            {
              dataSoureOrigin: originData ? JSON.parse(JSON.stringify(originData)) : [],
              dataSoureOrigin_old: originData ? JSON.parse(JSON.stringify(originData)) : [],
              dataSoureTarget: targetData ? JSON.parse(JSON.stringify(targetData)) : [],
              dataSoureTarget_old: targetData ? JSON.parse(JSON.stringify(targetData)) : [],
            },
            () => {
              this.tryCalc();
            },
          );
        }
      },
    });
  };
  //点击确定
  confirmAdust = (arr) => {
    const { dataSoureTarget, dataSoureOrigin, dataSoureOrigin_old, originId, targetId } = this.state;
    const {
      survivalManageM: { idList },
    } = this.props;
    this.props.dispatch({
      type: 'survivalManageM/confirmAdust',
      payload: {
        idList: arr,
      },
      callback: (type, data) => {
        if (type == 'success') {
          //重新获取拆分后流水和产品收益率、源产品资产列表和目标产品资产列表。
          this.setState({
            dataSoureTradeList: data.dataSource || [],
            columnsTrade: data.columns || [],
            updateYeild: new Date().getTime(),
          });
          this.clearIdList(); //确定之后 idList 清空 重新请求源产品和目标产品
          // this.queryAssignedAsset(originId,'origin','flag')
          this.queryAssignedAsset(targetId, 'target', 'flag');
        }
      },
    });
  };
  //源产品
  initTableOrigin = () => {
    const { columnsOrigin, dataSoureOrigin, selectedRowKeysUp } = this.state;
    const rowSelection = {
      //保存选中行
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ seletedRowsUp: selectedRows, selectedRowKeysUp: selectedRowKeys });
      },
      selectedRowKeys: selectedRowKeysUp,
      columnWidth: 50,
    };

    columnsOrigin &&
      columnsOrigin.map((item) => {
        if (item.key != 'operate') {
          item.width = parseFloat(86 / (columnsOrigin.length - 1)) + '%';
        }
        if (item.key == 'price' || item.key == 'marketValue') {
          item.type = 'money';
          if (item.key == 'price') {
            item.toFixed = 4;
          }
        }
        if (item.key == 'assetRate' || item.key == 'weight') {
          item.type = 'rate';
          if (item.key == 'assetRate') item.toFixed = 4;
        }
        if (item.key == 'allocation') {
          item.type = 'number';
        }
      });
    return (
      <TableC
        columns={columnsOrigin}
        dataSource={dataSoureOrigin}
        rowSelection={{
          ...rowSelection,
        }}
        hidePage={true}
        scroll={dataSoureOrigin && dataSoureOrigin.length > 5 ? { x: '100%', y: '178px' } : {}}
        rowKey='key'
      />
    );
  };
  //edit
  editInputNumber = (args, record) => {
    const { dataSoureTarget } = this.state;
    return (
      <InputNumber
        style={{ width: '100%' }}
        min={args == 'price' ? undefined : 0}
        precision={args == 'price' ? 4 : 0}
        onChange={(e) => {
          record[args] = e;
          dataSoureTarget.map((row, i) => {
            if (row.key == record.key) {
              row = record;
              dataSoureTarget[i] = record;
              this.setState({
                dataSoureTarget: [...dataSoureTarget],
              });
            }
          });
        }}
        value={record[args]}
      />
    );
  };
  //目标产品
  initTableTarget = () => {
    const { columnsTarget, dataSoureTarget, selectedRowKeysDown } = this.state;
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ seletedRowsDown: selectedRows, selectedRowKeysDown: selectedRowKeys });
      },
      selectedRowKeys: selectedRowKeysDown,
      columnWidth: 50,
      getCheckboxProps: (record) => ({
        disabled: record.isOrigin === true,
      }),
    };
    if (columnsTarget && columnsTarget[columnsTarget.length - 1].key != 'operate') {
      columnsTarget.push({
        key: 'operate',
        type: 'operate',
        title: '操作',
        // width:80,
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.clickEdit('edit', record);
            },
            rules: {
              hide: {
                relation: 'or',
                items: [
                  { key: 'isEdit', value: [true], relation: ['='] },
                  { key: 'isOrigin', value: [true], relation: ['='] },
                ],
              },
            },
          },
          {
            title: '保存',
            onClick: (record, index) => {
              this.saveRow(record);
            },
            rules: {
              hide: {
                relation: 'or',
                items: [
                  { key: 'isEdit', value: [false], relation: ['='] },
                  { key: 'isOrigin', value: [true], relation: ['='] },
                ],
              },
            },
          },
        ],
      });
    }
    columnsTarget &&
      columnsTarget.map((item) => {
        if (item.key != 'operate') {
          item.width = parseFloat(86 / (columnsTarget.length - 1)) + '%';
        }
        if (item.key == 'price' || item.key == 'marketValue') {
          item.type = 'money';
        }
        if (item.key == 'assetRate' || item.key == 'weight') {
          item.type = 'rate';
          if (item.key == 'assetRate') item.toFixed = 4;
        }
        if (item.key == 'allocation') {
          item.type = 'number';
          item.render = (text, record) => {
            if (record.isEdit) {
              return this.editInputNumber('allocation', record);
            } else {
              return text === 0 || text ? text : '--';
            }
          };
        }
        if (item.key == 'price') {
          item.render = (text, record) => {
            if (record.isEdit) {
              return this.editInputNumber('price', record);
            } else {
              return text === 0 || text ? fixedNum(text, 4) : '--';
            }
          };
        }
        if (item.key == 'marketValue') {
          item.render = (text, record) => {
            return text === 0 || text ? fixedNum(text) : '--';
          };
        }
      });
    return (
      <TableC
        columns={columnsTarget}
        dataSource={dataSoureTarget}
        hidePage={true}
        rowSelection={{
          ...rowSelection,
        }}
        scroll={dataSoureTarget && dataSoureTarget.length > 5 ? { x: '100%', y: '178px' } : {}}
        rowKey='key'
      />
    );
  };
  //点击向上箭头
  onClickUp = () => {
    const { seletedRowsDown, dataSoureTarget, dataSoureOrigin, originId, targetId } = this.state;
    if (!seletedRowsDown.length || originId == targetId) return;
    if (!dataSoureOrigin) return;
    if (dataSoureOrigin && !dataSoureOrigin.length) return;
    if (dataSoureTarget.findIndex((item) => item.isEdit == true) > -1) {
      message.warning('当前处于编辑状态!');
      return;
    }
    let msg;
    seletedRowsDown.map((row) => {
      if (row.productId != originId) {
        msg = '资产不在当前源产品中,不支持上移';
        message.error(`${row.assetCode}资产不在当前源产品中,不支持上移`);
        return;
      }
      let selectIndex = dataSoureTarget.findIndex((item) => item.key === row.key);
      //查看源产品资产中是否存在已选中数据,存在则给出index,不存在则为-1
      let originIndex = dataSoureOrigin.findIndex((item) => item.key === row.key);
      if (originIndex > -1) {
        // if(msg)return;
        //如果存在并且源产品资产存在源产品数量，则累加
        if (dataSoureOrigin[originIndex].allocation !== null && dataSoureOrigin[originIndex].allocation !== '' && !isNaN(dataSoureOrigin[originIndex].allocation)) {
          dataSoureOrigin[originIndex].allocation += dataSoureTarget[selectIndex].allocation;
        }
      } else {
        // if(msg)return;
        //如果不存在 则直接push到源产品表格
        dataSoureOrigin.unshift(rowObj);
      }
      // if(msg)return;
      //将选中数据从目标产品资产列表中移除
      dataSoureTarget.splice(selectIndex, 1);
    });
    //更新state里的数据
    this.setState({
      dataSoureOrigin: [...dataSoureOrigin],
      dataSoureTarget: [...dataSoureTarget],
      selectedRowKeysDown: undefined, //上方选中行index
      seletedRowsDown: [], //下方方选中行index
    });
  };
  //点击向下箭头
  onClickDown = () => {
    const { seletedRowsUp, dataSoureTarget, originId, targetId, dataSoureOrigin, dataSourceAssignedOld } = this.state;
    if (!seletedRowsUp.length || originId == targetId) return;
    if (!dataSoureTarget) return;
    if (dataSoureTarget && !dataSoureTarget.length) return;
    if (dataSoureTarget.findIndex((item) => item.isEdit == true) > -1) {
      message.warning('当前处于编辑状态!');
      return;
    }
    seletedRowsUp.map((row) => {
      // //找出当前选中的资产在目标产品资产数组中的index位置 ，为了移动之后，删除该行
      // let selectIndex=dataSoureTarget.findIndex(item => item.key === row.key );
      //查看源产品资产中是否存在已选中数据,存在则给出index,不存在则为-1
      let targetIndex = dataSoureTarget.findIndex((item) => item.key === row.key);
      if (targetIndex > -1) {
        //如果初始化后 添加过  则修改为可编辑
        // dataSoureTarget[targetIndex].allocation = 0; //数量和成本价可编辑，默认值是0；
        // dataSoureTarget[targetIndex].price = 0;
        dataSoureTarget[targetIndex].isEdit = true;
      } else {
        //如果不存在 直接push到目标产品表格 并且数量设置为0
        let rowObj = JSON.parse(JSON.stringify(row));
        rowObj.allocation = 0;
        rowObj.isEdit = true;
        rowObj.productId = originId;
        dataSoureTarget.unshift(rowObj);
      }
    });
    //更新state里的数据
    this.setState({
      dataSoureTarget: [...dataSoureTarget],
      selectedRowKeysUp: undefined,
      seletedRowsUp: [],
    });
  };
  totalTransfer = () => {
    this.props.goNext(2);
  };

  render() {
    const {
      search,
      originId,
      targetId,
      columnsTrade,
      dataSoureTradeList,
      selectProductList,
      dataSoureTarget_old,
      columnsOrigin,
      dataSoureOrigin,
      columnsTarget,
      dataSoureTarget,
      seletedRowsUp,
      seletedRowsDown,
    } = this.state;
    const { loading } = this.props;
    let sumRate1 = undefined;
    dataSoureOrigin &&
      dataSoureOrigin.map((item) => {
        sumRate1 = (sumRate1 || 0) + item.assetRate * 1 * (item.weight * 1);
      });
    let sumRate2 = undefined;
    dataSoureTarget &&
      dataSoureTarget.map((item) => {
        sumRate2 = (sumRate2 || 0) + item.assetRate * 1 * (item.weight * 1);
      });
    sumRate1 = sumRate1 === undefined ? sumRate1 : parseFloat(sumRate1 * 100).toFixed(4);
    sumRate2 = sumRate2 === undefined ? sumRate2 : parseFloat(sumRate2 * 100).toFixed(4);
    return (
      <div className={myStyle.TransferInside}>
        {search ? (
          <div>
            <div>
              <SecondHeaderC title={'资产分配'} />
            </div>
            <div style={{ marginBottom: '10px', display: 'flex' }}>
              <div style={{ marginRight: '10px' }}>
                <PrimaryC
                  title={'试算'}
                  onClick={() => {
                    this.tryCalc('init');
                  }}
                  disabled={dataSoureTarget && dataSoureOrigin ? false : true}
                  loading={loading.effects['survivalManageM/tryCalc'] == true}
                />
              </div>
              <div style={{ marginRight: '10px' }}>
                <PrimaryC
                  title={'确定'}
                  onClick={() => {
                    this.tryCalc('confirm');
                  }}
                  disabled={dataSoureTarget && dataSoureOrigin ? false : true}
                  loading={loading.effects['survivalManageM/confirmAdust'] == true}
                />
              </div>
              <div style={{ marginRight: '10px' }}>
                <PrimaryC
                  title={'二元自动转仓'}
                  onClick={() => {
                    this.tryCalc('smart');
                  }}
                  disabled={dataSoureTarget && dataSoureOrigin ? false : true}
                  loading={loading.effects['survivalManageM/smartTrans'] == true}
                />
              </div>
              <PrimaryC title={'整体转仓'} onClick={this.totalTransfer} />
            </div>
            <div className='assigned'>
              <div className='assignTitle'>
                <SelectC
                  form={this.props.form} // form对象
                  title='源产品' // 显示名称
                  dataIndex='originId' // Form识别的Item ID
                  dataSource={selectProductList}
                  onChange={(e) => this.queryAssignedAsset(e, 'origin')}
                  isMultiple={false}
                  optionTitle={true}
                  formItemLayout={{}}
                  onRef={(ref) => (this.originSelect = ref)}
                />
                <div className={'rateInit'}>
                  <span>原始收益率: {this.state.originInitRate !== undefined ? this.state.originInitRate + '%' : '--'}</span>
                </div>
                <div>
                  <span>当前收益率: {sumRate1 !== undefined ? sumRate1 + '%' : '--'}</span>
                </div>
              </div>
              {originId ? this.initTableOrigin() : <NoQueryC />}
            </div>
            <div className={'upDownDiv'}>
              <img
                src={
                  dataSoureOrigin && dataSoureOrigin.length && dataSoureTarget && dataSoureTarget.length && seletedRowsDown.length && originId != targetId ? upSelectedImg : upImg
                }
                onClick={this.onClickUp}
              />
              <img
                src={
                  dataSoureTarget && dataSoureTarget.length && dataSoureOrigin && dataSoureOrigin.length && seletedRowsUp.length && originId != targetId ? downSelectedImg : downImg
                }
                onClick={this.onClickDown}
              />
            </div>
            <div className='assigned'>
              <div className='assignTitle'>
                <SelectC
                  form={this.props.form} // form对象
                  title='目标产品' // 显示名称
                  dataIndex='targetId' // Form识别的Item ID
                  dataSource={selectProductList}
                  onChange={(e) => this.queryAssignedAsset(e, 'target')}
                  isMultiple={false}
                  optionTitle={true}
                  formItemLayout={{}}
                />
                <div className={'rateInit'}>
                  <span>原始收益率: {this.state.targetInitRate !== undefined ? this.state.targetInitRate + '%' : '--'}</span>
                </div>
                <div>
                  <span>当前收益率: {sumRate2 !== undefined ? sumRate2 + '%' : '--'}</span>
                </div>
              </div>
              {targetId ? this.initTableTarget() : <NoQueryC />}
            </div>
            <div style={{ marginTop: '20px' }}>
              <SecondHeaderC title='拆分后的交易流水' />
            </div>
            {dataSoureTradeList ? <TransactionFlow type='2' dataSource={dataSoureTradeList} columns={columnsTrade} /> : <NoQueryC />}
            <div style={{ marginTop: '20px' }}>
              <SecondHeaderC title='产品收益率' />
            </div>
            {search ? <ProductYield id={search} timestamp={this.state.updateYeild} /> : <NoQueryC />}
          </div>
        ) : (
          <NoQueryC />
        )}
      </div>
    );
  }
}
